package com.stormrage.xiangyu.view;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.stormrage.xiangyu.R;
import com.stormrage.xiangyu.plugin.Xiangyu;
import com.tencent.av.sdk.AVAudioCtrl;
import com.tencent.ilivesdk.ILiveConstants;
import com.tencent.ilivesdk.ILiveSDK;
import com.tencent.ilivesdk.business.callbusiness.ILVCallConstants;
import com.tencent.ilivesdk.business.callbusiness.ILVCallListener;
import com.tencent.ilivesdk.business.callbusiness.ILVCallManager;
import com.tencent.ilivesdk.core.ILiveLoginManager;
import com.tencent.ilivesdk.view.AVRootView;
import com.tencent.ilivesdk.view.AVVideoView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.tencent.ilivesdk.view.AVRootView.LAYOUT_GRAVITY_RIGHT;

/**
 * Created by zhanyonghui on 2016/10/25.
 */

public class VideoCallActivity extends Activity implements View.OnClickListener,ILVCallListener {

    private Button btnEndCall,btnCamera,btnMic,btnSpeaker;
    private String mHostId;
    private String formatTime;
    private int mCallId;
    private long mSecond = 0;
    private AVRootView avRootView;
    private boolean bCameraEnable = true;
    private boolean bMicEnalbe = true;
    private boolean bSpeaker = true;
    private int mCurCameraId = ILiveConstants.FRONT_CAMERA;
    private VideoTimerTask mVideoTimerTask;//计时器
    private TextView mVideoTime;
    private Timer mVideoTimer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        ILVCallConstants
        setContentView(R.layout.activity_video);

        // 添加通话回调
        ILVCallManager.getInstance().addCallListener(this);

        Intent intent = getIntent();
        mHostId = intent.getStringExtra("HostId");
        mCallId = intent.getIntExtra("CallId", 0);

        initView();
        checkPermission();

        ILVCallManager.getInstance().initAvView(avRootView);


    }

    private void initView() {
        mVideoTime = (TextView) findViewById(R.id.broadcasting_time);
        avRootView = (AVRootView) findViewById(R.id.av_root_view);
        avRootView.setGravity(LAYOUT_GRAVITY_RIGHT);
        btnEndCall = (Button) findViewById(R.id.btn_end);
    }

    @Override
    protected void onResume() {
        ILVCallManager.getInstance().onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        ILVCallManager.getInstance().onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mSecond!=0){
            Xiangyu.getInstance().sendVideoTime(mSecond);
        }
        ILVCallManager.getInstance().removeCallListener(this);
        ILVCallManager.getInstance().onDestory();
        if (null != mVideoTimer) {
            mVideoTimer.cancel();
            mVideoTimer = null;
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        ILVCallManager.getInstance().endCall(mCallId);
    }

    private void changeCamera() {

        if (bCameraEnable) {
            ILVCallManager.getInstance().enableCamera(mCurCameraId, false);
            avRootView.closeUserView(ILiveLoginManager.getInstance().getMyUserId(), true);
        } else {
            ILVCallManager.getInstance().enableCamera(mCurCameraId, true);
        }
        bCameraEnable = !bCameraEnable;
        btnCamera.setText(bCameraEnable ? R.string.tip_close_camera : R.string.tip_open_camera);
    }



    private void changeMic() {
        if (bMicEnalbe) {
            ILVCallManager.getInstance().enableMic(false);
        } else {
            ILVCallManager.getInstance().enableMic(true);
        }

        bMicEnalbe = !bMicEnalbe;
        btnMic.setText(bMicEnalbe ? R.string.tip_close_mic : R.string.tip_open_mic);
    }

    private void changeSpeaker() {
        if (bSpeaker) {
            ILiveSDK.getInstance().getAvAudioCtrl().setAudioOutputMode(AVAudioCtrl.OUTPUT_MODE_HEADSET);
        } else {
            ILiveSDK.getInstance().getAvAudioCtrl().setAudioOutputMode(AVAudioCtrl.OUTPUT_MODE_SPEAKER);
        }
        bSpeaker = !bSpeaker;
        btnSpeaker.setText(bSpeaker ? R.string.tip_set_headset : R.string.tip_set_speaker);
    }

    private void switchCamera() {
        mCurCameraId = (ILiveConstants.FRONT_CAMERA==mCurCameraId) ? ILiveConstants.BACK_CAMERA : ILiveConstants.FRONT_CAMERA;
        ILVCallManager.getInstance().switchCamera(mCurCameraId);
    }

    @Override
    public void onCallEstablish(int callId) {
        Xiangyu.getInstance().myNativeToJavascript(1007);
        btnEndCall.setVisibility(View.VISIBLE);

        // 设置点击小屏切换及可拖动
        final AVVideoView minorView = avRootView.getViewByIndex(1);
        minorView.setDragable(true);
        minorView.setGestureListener(new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                avRootView.swapVideoView(0, 1);
                //roomMgr.
                return false;
            }
        });

        //计时器
        mVideoTimer = new Timer(true);
        mVideoTimerTask = new VideoTimerTask();
        mVideoTimer.schedule(mVideoTimerTask, 1000, 1000);
        Xiangyu.getInstance().myNativeToJavascript(1005);
    }

    /**
     *  会话结束回调
     * @param callId
     * @param endResult 结束原因
     * @param endInfo   结束描述
     */
    @Override
    public void onCallEnd(int callId, int endResult, String endInfo) {
        Log.i("videocall","退出:"+endResult+":"+endInfo);
        if (mSecond!=0){
//            ILVCallConstants
            Xiangyu.getInstance().sendVideoTime(mSecond);
        }
        switch (endResult){
            //本地取消
            case 1:
                Xiangyu.getInstance().myNativeToJavascript(1009);
                break;
            //呼叫超时
            case 2:
                Xiangyu.getInstance().myNativeToJavascript(1010);
                break;
            //对方拒绝
            case 3:
                Xiangyu.getInstance().myNativeToJavascript(1008);
                break;
            //视频挂断
            case 4:
//                Toast.makeText(this,"通话关闭",Toast.LENGTH_SHORT).show();
                Xiangyu.getInstance().myNativeToJavascript(1006);
                break;
            //对方占线
            case 5:
                Xiangyu.getInstance().myNativeToJavascript(1010);
                break;
            case 6:
                Xiangyu.getInstance().myNativeToJavascript(1010);
                break;
            case 102:
//                Toast.makeText(this,"取消视频",Toast.LENGTH_SHORT).show();
                break;
        }

        finish();
    }

    @Override
    public void onException(int iExceptionId, int errCode, String errMsg) {

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_end){
            ILVCallManager.getInstance().endCall(mCallId);
        }
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    updateWallTime();
                    break;
            }
        }
    };

    /**
     * 记时器
     */
    private class VideoTimerTask extends TimerTask {
        public void run() {
            ++mSecond;
//            if (MySelfInfo.getInstance().getIdStatus() == Constants.HOST)
                mHandler.sendEmptyMessage(1);
        }
    }

    /**
     * 时间格式化
     */
    private void updateWallTime() {
        String hs, ms, ss;

        long h, m, s;
        h = mSecond / 3600;
        m = (mSecond % 3600) / 60;
        s = (mSecond % 3600) % 60;
        if (h < 10) {
            hs = "0" + h;
        } else {
            hs = "" + h;
        }

        if (m < 10) {
            ms = "0" + m;
        } else {
            ms = "" + m;
        }

        if (s < 10) {
            ss = "0" + s;
        } else {
            ss = "" + s;
        }
        if (hs.equals("00")) {
            formatTime = ms + ":" + ss;
        } else {
            formatTime = hs + ":" + ms + ":" + ss;
        }

//        if (Constants.HOST == MySelfInfo.getInstance().getIdStatus() && null != mVideoTime) {
//            SxbLog.i(TAG, " refresh time ");
            mVideoTime.setText(formatTime);
//        }
    }


    void checkPermission() {
        final List<String> permissionsList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if ((checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.CAMERA);
            if ((checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.RECORD_AUDIO);
            if ((checkSelfPermission(Manifest.permission.WAKE_LOCK) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.WAKE_LOCK);
            if ((checkSelfPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.MODIFY_AUDIO_SETTINGS);
            if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if ((checkSelfPermission(Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
            if (permissionsList.size() != 0) {
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        0);
            }
        }
    }
}
